



var fileTable = {
    /**
     * 文件信息列表
     */
    fileInfos:[],
    headers:[
        {name:'文件名', width:'40%'},
        {name:'修改日期', width:'20%'},
        {name:'文件类型', width:'20%'},
        {name:'大小', width:'20%'}
    ],
    retreatStack :null,
    advanceStack :null,
    menu:null,
    nowPath:'/',
    nowPathInsert:false,
    copyPath:null,
    deleteSource:false,
    wrapper:null,
    operations:null,
    keypress:-1,
    chooseItem:0,

    /**
     * 合并项
     * @param options
     */
    merge:function (options){
        for (let optionsKey in options) {
            this[optionsKey] = options[optionsKey]
        }
    },

    /**
     * 初始化
     * @param headers:{
     *     name:名称,
     *     width:宽度
     * }
     */
    init:function (options){
        styleClass.init();

        this.retreatStack = utils.newStack()
        this.advanceStack = utils.newStack()
        this.operations = {
            open:fileTable.clickOpen,
            auth:fileTable.auth,
            refresh:fileTable.refreshFileList,
            download:fileTable.clickDownload,
            up:fileTable.clickUp,
            rename:fileTable.clickRename,
            delete:fileTable.clickDelete,
            copy:fileTable.clickCopy,
            cut:fileTable.clickCut,
            paste:fileTable.clickPaste,
            newDir:fileTable.clickNewDir,
            shareText:fileTable.clickShareText
        }
        this.initKeyEvent()
        this.initPath()
        this.merge(options)
        this.createOperation();
        this.createTable();
        this.createMenu();
        $(window).resize(function (){
            var height = $('.share-operation-wrapper').css('height')
            $('.file-table-wrapper').css('margin-top',parseInt(height)-6+"px")
        })
        fileTable.autoAuth()
        fileTable.initVersion()
    },
    initKeyEvent:function () {
        $(document).keydown(function (e){
            fileTable.keypress = e.which
        })
        $(document).keyup(function (){
            fileTable.keypress = -1
        })
    }
    ,
    initPath:function (){
        fileTable.nowPath = localStorage.getItem("nowPath")
        if (fileTable.nowPath == null){
            fileTable.nowPath = "/"
        }
    },
    initVersion:function (){
      $.get('version',function (data){
          $('#version').text(data.version)
          $('#git').attr('href',data.git)
      })
    },
    storeNowPath:function (path){
        fileTable.nowPath = path;
        localStorage.setItem("nowPath",fileTable.nowPath)
    },

    createTable:function (){

        var table = $('<table class="file-list"></table>')
        var thead = $('<thead></thead>')
        var thead_tr = $('<tr class="file-list-header"></tr>')
        for (let header of this.headers) {
            var thead_td = $('<td></td>')
            thead_td.text(header.name)
            thead_td.css('width',header.width)
            thead_td.append($('<div class="file-list-header-pull"></div>'))
            thead_tr.append(thead_td)
        }
        thead.append(thead_tr)
        var tbody = $('<tbody class= "file-list-content"></tbody>')
        table.append(thead)
        table.append(tbody)
        var tableEmpty = $('<div class="file-list-empty">该文件夹为空</div>')
        var tableWrapper = $('<div class="file-table-wrapper"></div>')
        tableWrapper.css("margin-top",$('.share-operation-wrapper').height()+"px")
        tableWrapper.append(table)
        tableWrapper.append(tableEmpty)
        fileTable.wrapper.append(tableWrapper)
        this.headerPull();
    },
    createOperation:function (){
        var operationWrapper = $('<div class="share-operation-wrapper"></div>')
        operationWrapper.append($('<input type="file"  class="file-up-input" onchange="" multiple="multiple">'))
        var fileButtonWrapper = $('<div class="file-button-wrapper"></div>')
        fileButtonWrapper.append('<button class="file-button button-auth"><i class="fa fa-user-circle"></i>认证</button>')
        fileButtonWrapper.append('<button class="file-button button-refresh"><i class="fa fa-refresh"></i>刷新</button>')
        fileButtonWrapper.append('<button class="file-button button-download"><i class="fa fa-cloud-download"></i>下载</button>')
        fileButtonWrapper.append('<button class="file-button button-up"><i class="fa fa-upload"></i>上传</button>')
        fileButtonWrapper.append('<button class="file-button button-rename"><i class="fa fa-italic"></i>重命名</button>')
        fileButtonWrapper.append('<button class="file-button button-delete"><i class="fa fa-remove"></i>删除</button>')
        fileButtonWrapper.append('<button class="file-button button-copy"><i class="fa fa-copy"></i>复制</button>')
        fileButtonWrapper.append('<button class="file-button button-cut"><i class="fa fa-cut"></i>剪切</button>')
        fileButtonWrapper.append('<button class="file-button button-paste"><i class="fa fa-paste"></i>粘贴</button>')
        fileButtonWrapper.append('<button class="file-button button-newDir"><i class="fa fa-plus"></i>新建目录</button>')
        fileButtonWrapper.append('<button class="file-button button-shareText"><i class="fa fa-slideshare"></i>共享文本域</button>')
        var pathInputWrapper = $('<div class="path-input-wrapper"></div>')
        pathInputWrapper.append('<span class="path-action path-retreat path-action-invalid"><i class="fa fa-arrow-left"></i></span>')
        pathInputWrapper.append('<span class="path-action path-advance path-action-invalid"><i class="fa fa-arrow-right"></i></span>')
        pathInputWrapper.append('<input class="path-input" type="text" value="/">')
        var version = $('<div class="version"></div>')
        version.append(' <span>版本：</span>')
        version.append(' <span id="version" class="version-value"></span>')
        version.append(' <a id="git" href="https://gitee.com/gitee666/file-share-system">版本说明</a>')
        var shareAccount = $('<div class="share-account"></div>')
        shareAccount.append(' <span class="account-prefix">当前认证用户：</span>')
        shareAccount.append(' <span class="account"></span>')
        operationWrapper.append(fileButtonWrapper)
        operationWrapper.append(pathInputWrapper)
        operationWrapper.append(shareAccount)
        operationWrapper.append(version)
        pathInputWrapper.find('.path-input').keydown(function(event){
            if (event.which==13){
                var path =$(this).val();
                fileTable.setFileList(path)
            }
        });
        operationWrapper.find('.file-up-input').change(this.fileUpChange)
        pathInputWrapper.find('.path-retreat').click(this.pathRetreat)
        pathInputWrapper.find('.path-advance').click(this.pathAdvance)
        this.wrapper.append(operationWrapper)
    },
    /**
     * 生成菜单
     */
    createMenu:function (){
        var menuWrapper = $('<div class="menu-wrapper"></div>')
        var ul = $(' <ul class="menu">  </ul>')
        ul.append('<li class="menu-item menu-open menu-click">&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-folder-open"></i>打开</li>')
        ul.append('<li class="menu-item menu-download menu-click">&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-download"></i>下载</li>')
        ul.append('<li class="menu-item menu-rename menu-click">&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-italic"></i>重命名</li>')
        ul.append('<li class="menu-item menu-copy menu-click">&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-copy"></i>复制</li>')
        ul.append('<li class="menu-item menu-cut menu-click">&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-cut"></i>剪切</li>')
        ul.append('<li class="menu-item menu-delete menu-click">&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-remove"></i>删除</li>')
        ul.append('<li class="menu-item menu-auth menu-no-click">&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-user-circle"></i>认证</li>')
        ul.append('<li class="menu-item menu-refresh menu-no-click">&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-refresh"></i>刷新</li>')
        ul.append('<li class="menu-item menu-up menu-no-click">&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-upload"></i>上传</li>')
        ul.append('<li class="menu-item menu-paste menu-no-click">&nbsp;&nbsp;&nbsp;&nbsp;<i class="fa fa-paste"></i>粘贴</li>')
        menuWrapper.append(ul)
        $('body').append(menuWrapper)
        this.menu = menuWrapper;
        this.wrapper.append(menuWrapper)
        $(document).click(fileTable.menuHide)
        $(document).contextmenu(function (e){
            var mousePosition = utils.mousePosition(e);
            fileTable.menu.css('top',mousePosition.y+"px")
            fileTable.menu.css('left',mousePosition.x+"px")
            fileTable.menu.find('.menu-item').hide()
            fileTable.menu.find('.menu-no-click').show()
            fileTable.menu.show();
            return false;
        })
    },
    /**
     * 菜单显示
     * @param e
     * @returns {boolean}
     */
    menuShow:function (e){
        var chooseItem = $(this)
        $('.file-item').removeClass('file-item-click')
        chooseItem.addClass('file-item-click')
        var mousePosition = utils.mousePosition(e);
        fileTable.menu.css('top',mousePosition.y+"px")
        fileTable.menu.css('left',mousePosition.x+"px")
        fileTable.toggleFileOperation()
        fileTable.menu.find('.menu-item').hide()
        fileTable.menu.find('.menu-click').show()
        fileTable.menu.show();
        return false;
    },

    /**
     * 菜单隐藏
     * @param e
     */
    menuHide:function (e){
        fileTable.menu.hide();
    },
    /**
     * 表头拉扯事件
     */
    headerPull:function (){
        $('.file-list-header-pull').mousedown(function (e){
            var moveTd = $(this).parent();
            var tr = moveTd.parent()
            var nextTd = moveTd.next()
            var source = mousePosition(e)
            var trWidth = parseInt(tr.css('width'))
            var tdWidth = parseInt(moveTd.css('width'))
            var nextTdWidth = parseInt(nextTd.css('width'))
            $(document).mousemove(function (ev){
                var target = mousePosition(ev)
                var moveX = target.x - source.x;
                moveTd.css('width',((tdWidth+moveX)/trWidth)*100+"%")
                nextTd.css('width',((nextTdWidth-moveX)/trWidth)*100+"%")
            })
        })
        $(document).mouseup(function (){
            $(document).unbind('mousemove')
        })
    },
    /**
     * 设置表内容
     * @param fileInfos
     */
    setTableContent:function (fileInfos){
        this.fileInfos = fileInfos;
        var fileListContent = $('.file-list-content');
        fileListContent.html('')
        if (fileInfos.length == 0){
            $('.file-list-empty').show()
        }else{
            $('.file-list-empty').hide()
        }
        for (let i = 0; i < fileInfos.length; i++) {
            var itemData = fileInfos[i]
            var tr = $('<tr class="file-item" data-index="'+i+'"></tr>')
            styleClass.tableTdAppend(tr,itemData)
            tr.click(this.itemClick)
            tr.hover(this.itemHover)
            tr.contextmenu(this.menuShow);
            fileListContent.append(tr)
        }
    },
    /**
     * 获取文件信息
     * @param chooseItem 选中的一项
     * @returns {*}
     */
    getFileInfo:function (chooseItem){
        return this.fileInfos[chooseItem.attr('data-index')*1]
    },
    itemClick:function (){
        var clickItem = $(this)
        var fileInfo = fileTable.getFileInfo(clickItem)
        var dataIndex = clickItem.attr('data-index');
        if (fileTable.keypress == -1){
            if (clickItem.attr('class').indexOf('file-item-click') != -1){
                if(fileInfo.isFile){
                    fileTable.fileClick(fileInfo)
                }else{
                    fileTable.directoryClick(fileInfo)
                }
            }else{
                fileTable.itemChooseStyle(true,dataIndex)
            }
        }else if (fileTable.keypress == 16){
            fileTable.itemChooseStyle(true,fileTable.chooseItem,dataIndex)
        }else if (fileTable.keypress == 17){
            fileTable.itemChooseStyle(false,dataIndex)
        }
    },
    itemChooseStyle:function (flag,start,end){
        if (flag)$('.file-item').removeClass('file-item-click')
        if (end == null){
            $('.file-item').eq(start).addClass('file-item-click')
            fileTable.chooseItem = start;
        }else{
            if (start > end){
                fileTable.itemChooseStyle(false,end,start);
                return
            }
            for (let i = start; i <= end; i++) {
                $('.file-item').eq(i).addClass('file-item-click')
            }
        }
        fileTable.toggleFileOperation()
    },
    fileClick:function (fileInfo){
        var openFlag = fileInfo.openFlag
        var path = fileInfo.path
        if (openFlag == true || openFlag == "true"){
            window.open('open/'+fileInfo.name+'?path='+path+"&account="+fileTable.getAccount())
        }
    },
    directoryClick:function (fileInfo){
        var path = fileInfo.path
        fileTable.setFileList(path)
    },
    itemHover:function (){
        $('.file-item').hover(function (){
            var hoverItem = $(this)
            if (hoverItem.attr('class').indexOf('file-item-click') == -1){
                hoverItem.addClass('file-item-hover')
            }
        },function (){
            $(this).removeClass('file-item-hover')
        })
    },
    /**
     * 获取选中项
     * @returns {*|Window.jQuery|HTMLElement}
     */
    getChooseItem:function (){
        var chooseItem = $('.file-item-click')
        var chooseItems = []
        for (let i = 0; i < chooseItem.length; i++) {
            chooseItems.push($(chooseItem[i]))
        }
        return chooseItems;
    },
    /**
     * 获取选中项文件信息
     * @returns {*}
     */
    getChooseItemFileInfos:function (){
        var chooseItems =  this.getChooseItem()
        var fileInfos = []
        for (let chooseItem of chooseItems) {
            fileInfos.push(this.getFileInfo(chooseItem))
        }
        return fileInfos;
    },
    getChooseItemFileInfo:function (){
        var fileInfos = this.getChooseItemFileInfos();
        if (fileInfos.length == 0)return null;
        return fileInfos[0];
    },



    getAccount:function (){
        var account = localStorage.getItem('account');
        if (account == null){
            account = "";
        }
        return account;
    },
    autoAuth:function (account){
        if (account == null){
            account = fileTable.getAccount();
        }
        localStorage.setItem('account',account)
        this.authAjax('auth',null,function (data){
            if (data == ""){
                data = "匿名账户"
            }else{
                var index = data.indexOf("-")
                if (index != -1){
                    data = data.substring(0,index)
                }
            }
            $('.account').text(data)
            fileTable.setFileList(fileTable.nowPath,null,true)
        },'text')
    },
    authAjax:function (url,data,notify,dataType,method){
        if (dataType == null)dataType = 'json'
        $.ajax({
            url:url,
            type:method ==null ? 'get':method,
            dataType:dataType,
            data:data,
            headers:{'share-file-token':fileTable.getAccount()},
            success:notify
        })
    },
    auth:function (){
        var account = prompt("输入认证码",fileTable.getAccount())
        fileTable.autoAuth(account)
    },
    /**
     * 设置文件列表
     * @param path 路径
     * @param type null：点击时，true：前进，false：后退
     * @param flag 是否触发listenPath
     */
    setFileList: function (path,type,flag){
        fileTable.authAjax('fileList',{'path':path},function (res){
            var data = utils.getData(res)
            if (data == null){
                $('.path-input').val(fileTable.nowPath)
                return
            }
            fileTable.setTableContent(data.fileInfos)
            fileTable.nowPathInsert = data.insert
            $('.path-input').val(path)
            if (flag == null){
                fileTable.listenPath(type)
            }
            fileTable.toggleFileOperation()

            fileTable.storeNowPath(path)
        })
    },
    listenPath:function (type){
        if (type == null){
            fileTable.retreatStack.push(fileTable.nowPath);
            fileTable.advanceStack.clear()
        }else if (type){
            fileTable.retreatStack.push(fileTable.nowPath);
        }else{
            fileTable.advanceStack.push(fileTable.nowPath)
        }
        if (fileTable.retreatStack.size==0){
            utils.toggleClass($('.path-retreat'),'path-action-valid','path-action-invalid');
        }else{
            utils.toggleClass($('.path-retreat'),'path-action-invalid','path-action-valid');
        }
        if (fileTable.advanceStack.size == 0){
            utils.toggleClass($('.path-advance'),'path-action-valid','path-action-invalid');
        }else{
            utils.toggleClass($('.path-advance'),'path-action-invalid','path-action-valid');
        }
    },
    fileConvertOperationShow(fileInfo){
        var operationShows = {
            open:false,
            auth:true,
            refresh:true,
            download:false,
            up:false,
            rename:false,
            delete:false,
            copy:false,
            cut:false,
            paste:false,
            newDir:false,
            shareText:true
        }
        if (fileInfo != null){
            operationShows.copy = true;
            operationShows.rename = fileInfo.update;
            operationShows.cut = fileInfo.delete;
            operationShows.delete = fileInfo.delete;
            operationShows.download = fileInfo.isFile
            operationShows.open = !fileInfo.isFile || fileInfo.openFlag
        }
        if (fileTable.nowPathInsert){
            operationShows.up = true;
            operationShows.paste = fileTable.copyPath != null
            operationShows.newDir = true;
        }
        return operationShows;
    },

    toggleFileOperation:function (){
        var fileInfos = fileTable.getChooseItemFileInfos();
        var operationShows;
        if (fileInfos.length > 0){
            var operationShowsList = []
            for (let fileInfo of fileInfos) {
                operationShowsList.push(fileTable.fileConvertOperationShow(fileInfo))
            }
            operationShows = fileTable.mergeOperationShows(operationShowsList)
        }else{
            operationShows = fileTable.fileConvertOperationShow(null)
        }
        for (let key in operationShows) {
            if (operationShows[key]){
                $('.menu-'+key).off('click').click(fileTable.operations[key])
                $('.button-'+key).off('click').click(fileTable.operations[key])
                utils.toggleClass($('.menu-'+key),'menu-item-valid','menu-item-invalid')
                utils.toggleClass($('.button-'+key),'file-button-valid','file-button-invalid')
            }else{
                $('.menu-'+key).unbind('click',fileTable.operations[key])
                $('.button-'+key).unbind('click',fileTable.operations[key])
                utils.toggleClass($('.menu-'+key),'menu-item-invalid','menu-item-valid')
                utils.toggleClass($('.button-'+key),'file-button-invalid','file-button-valid')
            }
        }
    },
    mergeOperationShows:function (operationShowsList) {
        var res = operationShowsList[0]
        for (let i = 1; i < operationShowsList.length; i++) {
            for (let key in res) {
                res[key] = res[key] && operationShowsList[i][key]
            }
        }
        if (operationShowsList.length>1){
            res['open'] = false;
            res['rename'] = false;
        }
        return res
    },

    refreshFileList:function (){
        fileTable.setFileList(fileTable.nowPath,null,true)
    },
    pathRetreat:function (){
        var path = fileTable.retreatStack.pop()
        if (path != null){
            fileTable.setFileList(path,false)
        }
    },
    pathAdvance:function (){
        var path = fileTable.advanceStack.pop()
        if (path != null){
            fileTable.setFileList(path,true)
        }
    },
    clickUp:function (){
        $('.file-up-input').click();
    },
    fileUpChange:function (){
        var fileUp = this;
        var files = fileUp.files;
        if (files==null || files.length == 0)return
        var fileMap = {}
        for (let i = 0; i < files.length; i++) {
            fileMap[files[i].name] = files[i];
        }
        fileTable.authAjax('assertUpFiles',{path:fileTable.nowPath,filenames:Object.keys(fileMap).join('|')},function (res){
            var data = utils.getData(res)
            fileUp.value = ''
            var replaceFlag = false
            var filenames = Object.keys(data)
            if (filenames.length != 0){
                replaceFlag = confirm("替换这些文件吗？\n"+filenames.join('\n'))
            }
            if (replaceFlag){
                var noDeleteFilenames = [];
                for (let filename of filenames){
                    if (!data[filename]){
                        noDeleteFilenames.push(filename)
                    }
                }
                if (noDeleteFilenames.length != 0){
                    alert("不能替换，因为你没有以下文件的删除权限：\n"+filenames.join('\n'))
                    return
                }
            }else{
                for (let filename of filenames){
                    fileMap[filename] = null
                }
            }
            for (let key of Object.keys(fileMap)) {
                var file = fileMap[key]
                if (file != null){
                    addTask({
                        name:file.name,
                        upData:{'file':file,path:fileTable.nowPath},
                        url:'/upFile',
                        method:'post',
                        headers:{'share-file-token':fileTable.getAccount()},
                        performAfter:fileTable.upFileAfter
                    })
                }
            }

        })
    },
    upFileAfter:function (xhr){
        if (xhr.status == 200){
            utils.getData(xhr.response)
            fileTable.refreshFileList()
        }
    },
    clickRename:function (){
        var fileInfo = fileTable.getChooseItemFileInfo()
        if (fileInfo ==null)return
        var oldFilename = fileInfo.name;
        var newFilename = prompt("输入正确的文件名",oldFilename)
        if (newFilename != null && oldFilename != newFilename){
            fileTable.authAjax('rename',{path:fileInfo.path,newFilename:newFilename},function (res){
                utils.getData(res)
                fileTable.refreshFileList();
            })
        }
    },
    clickDelete:function (){
        var fileInfos = fileTable.getChooseItemFileInfos()
        if (fileInfos ==null)return
        var names = []
        var paths = []
        for (let fileInfo of fileInfos) {
            names.push(fileInfo.name)
            paths.push(fileInfo.path)
        }
        if (confirm('确认删除"'+names.join('|')+'"？')){
            fileTable. authAjax('deleteFile',{paths:paths.join('|')},function (res){
                utils.getData(res)
                fileTable.refreshFileList();
            })
        }
    },
    clickDownload:function (){
        var fileInfos = fileTable.getChooseItemFileInfos()
        if (fileInfos.length==0)return
        for (let fileInfo of fileInfos) {
            var aLink = document.createElement('a');
            var evt = document.createEvent('MouseEvents');
            evt.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            aLink.download = fileInfo.name;
            aLink.href = '/download?path='+fileInfo.path+'&account='+fileTable.getAccount();
            aLink.dispatchEvent(evt)
        }
    },
    clickCopy:function (){
        var fileInfos = fileTable.getChooseItemFileInfos()
        if (fileInfos ==null)return
        var paths = []
        for (let fileInfo of fileInfos) {
            paths.push(fileInfo.path)
        }
        fileTable.copyPath = paths
        fileTable.deleteSource = false;
        fileTable.toggleFileOperation()
    },
    clickCut:function (){
        fileTable.clickCopy();
        fileTable.deleteSource = true;
    },
    clickPaste:function (){
        if (fileTable.copyPath != null){
            fileTable.authAjax('paste',{sourcePaths:fileTable.copyPath.join("|"),targetPath:fileTable.nowPath,replace:true,deleteSource:fileTable.deleteSource},function (res){
                utils.getData(res)
                fileTable.copyPath = null
                fileTable.refreshFileList();
            })
        }
    },
    clickOpen:function (){
        var fileInfo = fileTable.getChooseItemFileInfo()
        if (fileInfo ==null)return
        if (fileInfo.isFile){
            fileTable.fileClick(fileInfo)
        }else{
            fileTable.directoryClick(fileInfo)
        }
    },
    clickNewDir:function (){
        var dirName = prompt("输入正确的目录名称","新建文件夹")
        if (dirName != null){
            fileTable.authAjax('newDir',{path:fileTable.nowPath,dirName:dirName},function (res){
                utils.getData(res)
                fileTable.refreshFileList();
            })
        }
    },
    clickShareText:function (){

        fileTable.authAjax('shareText',null,function (res){
            layer.open({
                title: '共享文本域',
                content: "<textarea style='width: 100%;height:100%;' oninput=\"save(this)\">"+res+"</textarea><script>function save(t){fileTable.authAjax(\"setShareText\",{shareText:t.value},null,null,'post')}</script>"
            });
        },'text')
    }

}




